package com.su.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.su.common.R;
import com.su.pojo.Category;
import com.su.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        categoryService.save(category);
        log.info("category {}", category);
        return R.success("添加成功");
    }

    /**
     * 分页展示分类信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getByPage(int page, int pageSize) {
        log.info("page {},pageSize {}", page, pageSize);
        Page<Category> page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //lqw.groupBy(Category::getType);
        lqw.orderByAsc(Category::getSort);
        categoryService.page(page1, lqw);
        return R.success(page1);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        return R.success(category);
    }

    /**
     * 修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
        boolean flag = categoryService.deleteById(id);
        if (flag) {
            return R.success("修改成功");
        } else {
            return R.error("有相关联的菜品或套餐，删除失败");
        }
    }

    /**
     * 根据条件查询分类
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getList(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort);
        List<Category> categoryList = categoryService.list(lqw);
        return R.success(categoryList);
    }
}
